package com.zfk.framework.case_loader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.util.Map;
import java.io.InputStream;

public class YamlCaseLoader {
    public static final  Logger logger = LogManager.getLogger(YamlCaseLoader.class);
    /**
     * 解析单个yaml文件中的case
     * 执行mvn test后 /src/main/resources目录下的文件会被自动复制到 target/classes下，需要类加载器来读取
     * 所以要先处理路径，转换成相对路径
     * @param yamlFilepath 单个测试用例yaml文件名，以相对路径的形式
     * @return 返回当前文件的所有用例数据 是个Map
     * @throws IOException  IO
     */
    public static Map<String,Map<String,Object>> readYamlCase (String yamlFilepath) throws IOException{
        Yaml yaml = new Yaml();
        ClassLoader classLoader=YamlCaseLoader.class.getClassLoader();
        String yamlCasePath =relativeYamlCasePath(yamlFilepath);
        try(InputStream inputStream=classLoader.getResourceAsStream(yamlCasePath)){
            if (inputStream== null) {
                logger.error("无法找到文件{},请确认文件是否存在",yamlCasePath);
                throw new IllegalArgumentException("无法找到用例文件"+yamlCasePath);
            }
            //这么读需严格保证单条测试用例按照样本文件的结构编写，否则就会报错
            //当前版本不对yaml文件的结构校验，仅对字段进行校验
            Map<String, Map<String, Object>> yamlData = yaml.load(inputStream);
            if (yamlData == null || yamlData.isEmpty()) {
                logger.error("文件{}为空，请填写内容",yamlCasePath);

                throw new IllegalArgumentException("YAML 文件 " + yamlCasePath+ " 为空！");
            }
            logger.info("成功读取{}文件，包含{}个测试用例",yamlCasePath,yamlData.size());
            return yamlData;//Map<String,Map<String,Object>>
        }
    }

    /**
     * 路径转换，将绝对路径转换成相对路径，去掉/src/main/resources，
     * @param yamlFilepath 传入的是绝对路径
     * @return 返回相对路径
     */
    public static String relativeYamlCasePath(String yamlFilepath){
        String relativePath = yamlFilepath.replace("\\","/");
        if (relativePath.startsWith("/src/main/resources")){
            return relativePath.substring("/src/main/resources".length());
        }
        if (relativePath.startsWith("./src/main/resources/")){
            return relativePath.substring("./src/main/resources/".length());
        }
        return relativePath;
    }
}
